import collections
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def getMinimumDifference(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        stack = collections.deque([root])
        while stack[-1].left:
            stack.append(stack[-1].left)
        prev = None
        min_val = float('inf')
        while stack:
            node = stack.pop()
            if prev:
                min_val = min(node.val - prev.val, min_val)
            prev = node
            if node.right:
                node = node.right
                while node:
                    stack.append(node)
                    node = node.left
        return min_val


